package team.yg.asset.interpector;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import team.yg.asset.constant.CommonConstant;
import team.yg.asset.context.BaseContext;
import team.yg.asset.properties.JwtProperties;
import team.yg.asset.resful.Result;
import team.yg.asset.utils.JWTUtil;

/**
 * 登录拦截器
 * */
@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果是login请求，直接放行
        String url = request.getRequestURI();
        log.info("请求路径：{}", url);
        if(url.contains("/login")){
            return true;
        }


        //1.获取token令牌
        String token = request.getHeader(jwtProperties.getTokenName());
        //2.判断是否为空。为空，返回错误信息，然后拦截
        if (StringUtils.isEmpty(token)) {
            //提示请登录
            String jsonStr = JSONUtil.toJsonStr(Result.error(CommonConstant.LOGIN_FAIRE));
            response.getWriter().write(jsonStr);
            return false;
        }

        //校验令牌
        try {
            log.info("开始校验，token为：{}",token);
            //3. token不为空，解析令牌
            Claims claims = JWTUtil.parseJWT(jwtProperties.getSecretKey(), token);
            //4.获取用户id
            Long userId = Long.valueOf(claims.get("userId").toString());
            //5.将用户id存入ThreadLocal
            BaseContext.setCurrentId(userId);
            //放行
            return true;
        } catch (Exception e) {
            //校验失败，拦截,返回错误信息
            log.info("校验失败");
            String jsonStr = JSONUtil.toJsonStr(Result.error(CommonConstant.LOGIN_VERIFY_FAIRE));
            response.getWriter().write(jsonStr);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //检查有无ThreadLocal资源
        if(BaseContext.getCurrentId() != null){
            BaseContext.removeCurrentId();
        }
    }
}
